import os
import time
from typing import List, Dict

import crawlertool as tool


class SpiderTftExploitList(tool.abc.SingleSpider):
    """WeGame云顶之弈比赛记录爬虫：游戏场次列表"""

    _HEADERS = {"Accept-Encoding": "gzip",
                "Host": "mlol.qt.qq.com",
                "Connection": "Keep-Alive",
                "user-agent": "okhttp/3.12.0"}

    def running(self, skey, summoner, start_time, end_time) -> List[Dict]:
        params = {
            "user_id": summoner,
            "scene": "tft_mlol",
            "plat": "android",
            "version": "9914",
            "game_area": "1",
            "login_account_type": "1"
        }

        next_baton = None
        exploit_list = []

        # 执行请求
        for i in range(100):

            print("执行第", i + 1, "次请求...")

            if next_baton:
                params["baton"] = next_baton

            # 请求召唤师比赛记录列表(需要cookies,p_skey可以不需要,可以使用bacon参数控制翻页)
            response = tool.do_request(
                url="https://mlol.qt.qq.com/gorpc/exploit/exploit/query_player_exploit_list/proxy",
                params=params,
                headers=self._HEADERS,
                cookies={"l_uin": "o13578660",
                         "p_uin": "o13578660",
                         "uin": "o13578660",
                         "skey": skey},
                verify=False)
            exploit_json = response.json()

            if "info" not in exploit_json:
                break
            if "exploit_list" not in exploit_json["info"]:
                break
            if "next_baton" not in exploit_json["info"]:
                break
            next_baton = exploit_json["info"]["next_baton"]

            if exploit_json["info"]["exploit_list"] is None:
                break

            for exploit_item in exploit_json["info"]["exploit_list"]:
                if "exploit_id" not in exploit_item:
                    continue
                if "end_time" not in exploit_item:
                    continue
                if "game_match_type" not in exploit_item:
                    continue
                if "specific_user_exploit" not in exploit_item:
                    continue
                if "user_id" not in exploit_item["specific_user_exploit"]:
                    continue
                if exploit_item["end_time"] < start_time:
                    break
                if exploit_item["end_time"] < end_time:
                    exploit_list.append({
                        "exploit_id": exploit_item["exploit_id"],
                        "end_time": exploit_item["end_time"],
                        "user_id": exploit_item["specific_user_exploit"]["user_id"],
                        "game_match_type": exploit_item["game_match_type"]
                    })

        return exploit_list


# ------------------- 单元测试 -------------------
if __name__ == "__main__":
    # 设置不需要代理的环境变量(解决request.exceptions.ProxyError:HTTPSConnectionPool的问题)
    os.environ["NO_PROXY"] = "mlol.qt.qq.com"

    print(SpiderTftExploitList().running(
        skey="MK3lj8yMoH",
        summoner="42b0a5ed-c1d9-4246-ac1b-67b02069b32c",
        start_time=int(time.mktime(time.strptime("2020-01-18 20:00:00", "%Y-%m-%d %H:%M:%S"))),  # 时间范围开始时间
        end_time=int(time.mktime(time.strptime("2020-01-19 19:59:59", "%Y-%m-%d %H:%M:%S")))  # 时间范围结束时间
    ))
